package com.xiangxue.kotlinproject.databse

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

// java  entities = {}
// kt entities = []
@Database(entities = [Student::class], version = 1,exportSchema = false)
abstract class StudentDatabase : RoomDatabase() {

    // 最终给用户的就是 DAO
    abstract fun getStudentDao() : StudentDao

    companion object {

        private var INSTANCE : StudentDatabase ? = null

        // Application
        fun getDatabase(context: Context) : StudentDatabase ? {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context,
                    StudentDatabase::class.java, "student_database.db")
                    .allowMainThreadQueries() // 允许在主线程运行
                    //.fallbackToDestructiveMigration()//强制升级   数据丢失
                    //.addMigrations(MIGRATION_1_2)//升级数据库
                    .build()
            }
            return INSTANCE

        }

        fun getDatabase() : StudentDatabase? = INSTANCE
        //升级后version也修改   version = 2
        val MIGRATION_1_2 = object  : Migration(1,2){
            override fun migrate(database: SupportSQLiteDatabase) {
                //在这里用sql脚本完成数据变化
                database.execSQL("alter table Student add column name String not null default 'hello' ")
            }
        }
    }

}